package com.lin.util.pdfutil;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;


/**
 * 图片转pdf工具
 *
 * @author linqiankun
 */
@Slf4j
public class PicToPdfUtil {

    /**
     * 将图片转换为pdf，bug
     *
     * @param inputStream 图片输入流
     * @return pdf 输出流
     */
    public static ByteArrayOutputStream picToPdf1(InputStream inputStream) {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //创建pdf文档
        PdfDocument document = new PdfDocument();
        //添加页面
        PdfPageBase pdfPageBase = document.getPages().add();
        //加载图片
        PdfImage pdfImage = PdfImage.fromStream(inputStream);

        //绘制图片到pdf并设置其在pdf文件中的位置和大小
        double width = getImgWidth(inputStream) / pdfPageBase.getActualBounds(true).getWidth();
        double height = getImgHeight(inputStream) / pdfPageBase.getActualBounds(true).getHeight();

        double fitRate = Math.max(width, height);
        double fitWidth = getImgWidth(inputStream) / fitRate * 0.707f;
        double fitHeight = getImgHeight(inputStream) / fitRate * 1.0f;

        pdfPageBase.getCanvas().drawImage(pdfImage, 0, 0, fitWidth, fitHeight);

        //保存并关闭
        document.saveToStream(outputStream);
        document.close();

        return outputStream;
    }

    /**
     * @param inputStream 图片文件
     * @return 图片的宽度
     */
    private static double getImgHeight(InputStream inputStream) {
        BufferedImage src = null;
        int ret = -1;
        try {
            src = javax.imageio.ImageIO.read(inputStream);
            ret = src.getWidth(null);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return ret;
    }

    /**
     * @param inputStream 图片文件
     * @return 图片的高度
     */
    private static double getImgWidth(InputStream inputStream) {
        BufferedImage src = null;
        int ret = -1;
        try {
            src = javax.imageio.ImageIO.read(inputStream);
            ret = src.getHeight(null);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return ret;
    }


    /**
     * 图片转pdf,位置不准确
     *
     * @param imgFilePath 图片文件路径
     * @param pdfFilePath pdf文件路径
     * @return 转换成功
     * @throws IOException 文件读取异常
     */
    public static boolean imgToPdf2(String imgFilePath, String pdfFilePath) throws IOException {
        File file = new File(imgFilePath);
        if (file.exists()) {
            Document document = new Document();
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(pdfFilePath);
                PdfWriter.getInstance(document, fos);
                // 添加PDF文档的某些信息，比如作者，主题等等
                document.addAuthor("linqiankun");
                document.addSubject("linqiankun");
                // 设置文档的大小
                document.setPageSize(PageSize.A4);
                // 打开文档
                document.open();
                // 写入一段文字
                // document.add(new Paragraph("JUST TEST ..."));
                // 读取一个图片
                Image image = Image.getInstance(imgFilePath);
                float imageHeight = image.getScaledHeight();
                float imageWidth = image.getScaledWidth();
                int i = 0;
                while (imageHeight > 500 || imageWidth > 500) {
                    image.scalePercent(100 - i);
                    i++;
                    imageHeight = image.getScaledHeight();
                    imageWidth = image.getScaledWidth();
                    System.out.println("imageHeight->" + imageHeight);
                    System.out.println("imageWidth->" + imageWidth);
                }

                image.setAlignment(Image.ALIGN_CENTER);
                // 设置图片的绝对位置
                // image.setAbsolutePosition(0, 0);
                // image.scaleAbsolute(500, 400);
                // 插入一个图片
                document.add(image);
            } catch (DocumentException | IOException de) {
                log.error(de.getMessage());
            }
            document.close();
            if (fos != null) {
                fos.flush();
                fos.close();
            }
            return true;
        } else {
            return false;
        }
    }


    /**
     * 图片转pdf
     *
     * @param imagePath 图片路径
     * @param pdfPath   pdf路径
     * @throws DocumentException 文本异常
     * @throws IOException       流异常
     */
    public static void imageToPdf3(String imagePath, String pdfPath) throws IOException, DocumentException {
        BufferedImage img = ImageIO.read(new File(imagePath));
        FileOutputStream fos = new FileOutputStream(pdfPath);
        Document doc = new Document(null, 0, 0, 0, 0);
        doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
        Image image = Image.getInstance(imagePath);
        PdfWriter.getInstance(doc, fos);
        doc.open();
        doc.add(image);
        doc.close();
    }


}
